const router = require('express').Router();
const {asyncHandler} = require('../middleWare/getSentResult');
const ProjectServer = require('../server/projedctServ');
const {setR,getR,delR,caseTime} = require("../server/redisServe");
const { apiGetProject } = require('../routerConfig')
router.get("/getProject",asyncHandler(async(req,res,next)=>{

    const limit = req.query.limit || 10;
    const skip = req.query.skip || 1;
    res.header("Cache-Control",`max-age=0`);
    const Cresult = await getR(4,req.originalUrl);
    if(Cresult) return JSON.parse(Cresult);
    const result = await ProjectServer.getProject(limit,skip);
    setR(4,apiGetProject,JSON.stringify(result),{EX:caseTime});
    return result;

}))

router.post("/addProject",asyncHandler(async(req,res,next)=>{
    
    const {name,github,gitee,discription,thumb,Url,language} = req.body;
    
    if(!(name && github && gitee && discription && thumb && Url && language )) return '条件不满足'
    const result = await ProjectServer.addProject(name,github,gitee,discription,thumb,Url,language)
    await delR(4,apiGetProject)
    return result;

}))

router.post('/upProject', asyncHandler( async(req,res,next)=>{
    const {_id,name,github,gitee,discription,thumb,Url,language} = req.body
    if(!(_id && name  && discription && thumb  )) return '条件不满足'
    try {
        const result = await ProjectServer.upProject(_id,name,github,gitee,discription,thumb,Url,language)
        await delR(4,apiGetProject)
        return result;
    } catch(e) {
        return e.name
    }

} ))

router.post('/delProject', asyncHandler( async(req,res,next)=>{
    const { _id } = req.body;
    if(!_id) return '缺少_id'
    try {
        const result = await ProjectServer.delProject(_id)
        if(result.deletedCount === 1) {
            await delR(4,apiGetProject)
            return true
        } else {
            return false
        }
    } catch(e) {
        return e.name
    }
}))

module.exports = router;
